{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chat_models.tongyi import ChatTongyi\n",
    "from langchain.embeddings.dashscope import DashScopeEmbeddings\n",
    "from langchain.vectorstores.chroma import Chroma\n",
    "from dotenv import load_dotenv\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "load_dotenv()\n",
    "api_key = os.environ.get(\"DASHSCOPE_API_KEY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_17424/1902959567.py:3: LangChainDeprecationWarning: The class `Chroma` was deprecated in LangChain 0.2.9 and will be removed in 1.0. An updated version of the class exists in the :class:`~langchain-chroma package and should be used instead. To use it run `pip install -U :class:`~langchain-chroma` and import as `from :class:`~langchain_chroma import Chroma``.\n",
      "  vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding)\n"
     ]
    }
   ],
   "source": [
    "persist_directory = \"./docs/chroma/matplotlib/\"\n",
    "embedding = DashScopeEmbeddings(dashscope_api_key=api_key)\n",
    "vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='你好！有什么我可以帮你的吗？😊', additional_kwargs={}, response_metadata={'model_name': 'qwen-flash', 'finish_reason': 'stop', 'request_id': '83d94ae6-abfc-4674-81e8-dfff1e0e9df4', 'token_usage': {'input_tokens': 9, 'output_tokens': 9, 'cached_tokens': 0, 'total_tokens': 18}}, id='run--521f9a49-7ac1-4623-9004-0fc5fc202797-0')"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "llm = ChatTongyi(api_key=api_key, model=\"qwen-flash\")\n",
    "llm.invoke(\"你好\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/tmp/ipykernel_17424/1419636061.py:21: LangChainDeprecationWarning: The method `Chain.__call__` was deprecated in langchain 0.1.0 and will be removed in 1.0. Use :meth:`~invoke` instead.\n",
      "  result = qa_chain({\"query\":question})\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这门课的主题是数据可视化，重点介绍使用Matplotlib进行2D图形绘制，包括基本绘图、子图布局、两种绘图接口（OO模式与pyplot模式）以及实际应用示例。  \n",
      "谢谢你的提问！\n"
     ]
    }
   ],
   "source": [
    "# 创建基于模板的检索链\n",
    "from langchain.prompts import PromptTemplate\n",
    "template = \"\"\"\n",
    "使用以下的上下文来回答最后的问题。如果你不知道答案，就说你不知道，不要试图编造答案。最多使用三句话。尽量使答案简明扼要。总是在回答的最后说”谢谢你的提问！“。\n",
    "{context}\n",
    "问题：\n",
    "{question}\n",
    "\"\"\"\n",
    "\n",
    "QA_CHIAN_PROMPT = PromptTemplate.from_template(template)\n",
    "\n",
    "from langchain.chains import RetrievalQA\n",
    "question = \"这门课的主题是什么？\"\n",
    "qa_chain = RetrievalQA.from_chain_type(\n",
    "    llm,\n",
    "    retriever = vectordb.as_retriever(),\n",
    "    return_source_documents=True,\n",
    "    chain_type_kwargs={\"prompt\":QA_CHIAN_PROMPT}\n",
    ")\n",
    "\n",
    "result = qa_chain({\"query\":question})\n",
    "print(result[\"result\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 记忆"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.memory import ConversationBufferMemory\n",
    "memory = ConversationBufferMemory(memory_key=\"chat_history\",return_messages=True )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains import ConversationalRetrievalChain\n",
    "retriever = vectordb.as_retriever()\n",
    "qa = ConversationalRetrievalChain.from_llm(\n",
    "    llm,\n",
    "    retriever = retriever,\n",
    "    memory=memory\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这门课程主要聚焦于 **Matplotlib 数据可视化**，而不是系统性地教授 Python 编程语言本身。不过，课程内容会使用 Python 作为实现工具，因此你会在学习过程中接触到 Python 的基本语法和编程概念（如变量、列表、函数等），尤其是与数据处理和绘图相关的部分。\n",
      "\n",
      "总结来说：\n",
      "- **不会专门教 Python 入门知识**（比如变量定义、循环、条件语句等基础语法）；\n",
      "- **但会用到 Python 来实现数据可视化操作**，所以你需要具备一定的 Python 基础才能跟上课程内容。\n",
      "\n",
      "如果你还没有学过 Python，建议先掌握一些基础语法，再进入本课程学习会更顺利。\n"
     ]
    }
   ],
   "source": [
    "question = \"这门课会学习Python吗？\"\n",
    "result = qa.invoke(question)\n",
    "print(result[\"answer\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'chat_history': [HumanMessage(content='这门课会学习Python吗？', additional_kwargs={}, response_metadata={}),\n",
       "  AIMessage(content='这门课程主要聚焦于 **Matplotlib 数据可视化**，而不是系统性地教授 Python 编程语言本身。不过，课程内容会使用 Python 作为实现工具，因此你会在学习过程中接触到 Python 的基本语法和编程概念（如变量、列表、函数等），尤其是与数据处理和绘图相关的部分。\\n\\n总结来说：\\n- **不会专门教 Python 入门知识**（比如变量定义、循环、条件语句等基础语法）；\\n- **但会用到 Python 来实现数据可视化操作**，所以你需要具备一定的 Python 基础才能跟上课程内容。\\n\\n如果你还没有学过 Python，建议先掌握一些基础语法，再进入本课程学习会更顺利。', additional_kwargs={}, response_metadata={})]}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "memory.load_memory_variables({})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "学习这门课程需要具备一定的 Python 基础，是因为 Matplotlib 是一个基于 Python 的数据可视化库，其使用依赖于 Python 的语法、数据结构（如列表、数组、字典等）以及编程逻辑。以下是具体原因：\n",
      "\n",
      "1. **理解代码结构**：课程中的示例代码大量使用 Python 语法，例如变量定义、函数调用、循环和条件判断等。如果没有基础，难以理解代码的执行流程。\n",
      "\n",
      "2. **处理数据**：Matplotlib 经常与 NumPy、Pandas 等数据分析库结合使用，这些库都需要对 Python 的数组操作、数据框（DataFrame）等有基本了解。\n",
      "\n",
      "3. **灵活控制绘图**：高级绘图功能（如自定义坐标轴、图例、颜色、样式等）需要通过 Python 代码进行精细设置，只有掌握 Python 才能实现复杂图表的定制。\n",
      "\n",
      "4. **在 Jupyter Notebook 中运行**：课程中推荐使用 Jupyter Notebook 进行实践，这要求学习者熟悉 Python 的交互式编程环境，能够正确运行代码块并查看输出结果。\n",
      "\n",
      "因此，具备一定的 Python 基础是顺利学习和掌握 Matplotlib 数据可视化技能的前提。\n"
     ]
    }
   ],
   "source": [
    "question = \"为什么需要这一前提？\"\n",
    "result = qa.invoke(question)\n",
    "print(result[\"answer\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
